﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using HYCodeBase.WinForm;

namespace HYView
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdZoomViewToSlectedArea : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			UIDocument activeUIDocument = cmdData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			Selection selection = cmdData.Application.ActiveUIDocument.Selection;
			if (CmdZoomViewToSlectedArea._hWndRevit == null)
			{
				CmdZoomViewToSlectedArea._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			List<string> list = new List<string>();
			IList<UIView> openUIViews = activeUIDocument.GetOpenUIViews();
			foreach (UIView uiview in openUIViews)
			{
				Autodesk.Revit.DB.View view = document.GetElement(uiview.ViewId) as Autodesk.Revit.DB.View;
				list.Add(view.Name);
			}
			ZoomViewToSlectedAreaForm zoomViewToSlectedAreaForm = new ZoomViewToSlectedAreaForm(cmdData, document.ActiveView, list);
			zoomViewToSlectedAreaForm.Show(CmdZoomViewToSlectedArea._hWndRevit);
			Result result;
			for (;;)
			{
				Element element;
				try
				{
					Reference reference = selection.PickObject((Autodesk.Revit.UI.Selection.ObjectType)1, "请选择需要缩放的对象");
					element = document.GetElement(reference);
				}
				catch
				{
					zoomViewToSlectedAreaForm.Close();
					result = Autodesk.Revit.UI.Result.Failed;
					break;
				}
				using (List<int>.Enumerator enumerator2 = zoomViewToSlectedAreaForm.GetSelectViewIndex().GetEnumerator())
				{
					while (enumerator2.MoveNext())
					{
						int index = enumerator2.Current;
						Autodesk.Revit.DB.View view2 = document.GetElement(openUIViews[index].ViewId) as Autodesk.Revit.DB.View;
						BoundingBoxXYZ boundingBoxXYZ = element.get_BoundingBox(view2);
						if (boundingBoxXYZ != null)
						{
							openUIViews[index].ZoomAndCenterRectangle(boundingBoxXYZ.Min, boundingBoxXYZ.Max);
						}
					}
					continue;
				}
				break;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;
	}
}
